import {Inject, Injectable} from '@angular/core';
import {Observable, of} from 'rxjs';
import {Washer, WasherOpenId, WasherToAdd, WasherToUpdate} from './washer.model';
import {tap} from 'rxjs/internal/operators';
import {AuthHttp} from '../../shared/auth.http';
import {APP_CONFIG} from '../../config/app.config';

@Injectable()
export class WasherService {
  private baseUrl: string;
  private currentSelectedWasher: Washer;

  get currentWasher(): Washer {
    return this.currentSelectedWasher;
  }

  set currentWasher(currentSelectedWasher: Washer) {
    this.currentSelectedWasher = currentSelectedWasher;
  }

  constructor(@Inject(APP_CONFIG) appConfig,
              private http: AuthHttp) {
    this.baseUrl = appConfig.endpoints.base;
  }

  getWasherList(): Observable<Washer[]> {
    // return this.http.get<Washer[]>(this.baseUrl + 'ops/worker/listall').pipe(
    //   tap( () => console.log('get washer list successful...'), () => console.error('get washer list failed...'))
    // );
    return this.http.get<Washer[]>(this.baseUrl + 'be_ops/v2/worker/listeveryworker').pipe(
      tap( () => console.log('get washer list successful...'), () => console.error('get washer list failed...'))
    );
  }

  getOpenId(phoneNumber: string): Observable<string> {
    return this.http.get<string>(this.baseUrl + 'be_ops/v2/worker/openid/' + phoneNumber, null, 'text').pipe(
      tap((data) => { console.log('get washer openid successful...'); console.log(data); },
        (err) => { console.error('get washer openid failed...'); console.error(err); })
    );
    // const openId = of('akdfiwekrewrowekl12312kdfaj');
    // return openId;
  }
  addWasher(washer: WasherToAdd): Observable<boolean> {
    return this.http.post<boolean>(this.baseUrl + 'be_ops/v2/worker/new', washer).pipe(
      tap( () => console.log('add washer successful...'),
        (err) => { console.error('add washer failed...'); console.error(err); })
    );
  }
  deleteWasher(washerId: string): Observable<boolean> {
    console.log('inside deleteWasher...');
    return this.http.get<boolean>(this.baseUrl + 'be_ops/v2/worker/disable/' + washerId, null).pipe(
      tap(() => console.log('delete washer successful...'),
        (err) => { console.error('delete washer failed...'); console.error(err); })
    );
  }
  updateWasher(washer: WasherToUpdate): Observable<boolean> {
    return this.http.put<boolean>(this.baseUrl + 'be_ops/v2/worker/update', washer).pipe(
      tap(() => console.log('update washer successful...'),
        (err) => { console.error('update washer failed...'); console.error(err); })
    );
  }
}
